import { PullToRefresh, List, InfiniteScroll, Empty, Loading } from 'antd-mobile';
import { SimpleListViewProps } from './type';
import styles from './index.less';
import { useRef, forwardRef, useImperativeHandle, useState } from 'react';
import { useEffect } from 'react';
import { getMessage, TextWidget } from '@inbiz/react';

function RefreshContainer(props: any) {
  return props?.onRefresh ? <PullToRefresh {...props} /> : props.children;
}

function SimpleListView(props: SimpleListViewProps, ref?: any) {
  const listRef = useRef<any>();
  const [hasMore, _hasMore] = useState(true);
  const loaded = useRef<boolean>(false);
  useEffect(() => {
    if (!loaded.current) {
      loaded.current = true;
      setTimeout(() => {
        _hasMore(!!props.hasMore);
      }, 500);
    } else {
      _hasMore(!!props.hasMore);
    }
  }, [props.hasMore]);
  useImperativeHandle(ref, () => {
    return {
      scroll: (x: number, y: number) => {
        listRef.current?.firstElementChild?.scroll(x, y);
      },
    };
  });

  return (
    <div className={styles.simpleList} style={props.style} ref={listRef}>
      <RefreshContainer onRefresh={props?.onRefresh}>
        {props.loading ? (
          <div className={styles.loading}>
            <Loading color="primary" />
          </div>
        ) : props.dataSource.length ? (
          <List style={{ border: 'none', backgroundColor: 'transparent' }}>
            {props.dataSource.map(props.renderRow)}
            {props.loadMore ? (
              <InfiniteScroll loadMore={props.loadMore} hasMore={props.hasMore}>
                {props.loadingMore ? (
                  <Loading color="primary" />
                ) : (
                  <TextWidget>ECM.noMore</TextWidget>
                )}
              </InfiniteScroll>
            ) : null}
          </List>
        ) : hasMore || props.loading || props.loadingMore ? null : (
          <Empty
            style={{ padding: '64px 0' }}
            description={props.emptyText || getMessage('ECM.noData')}
          />
        )}
      </RefreshContainer>
    </div>
  );
}

export default forwardRef(SimpleListView);
